package com.epoint.netty.doublesocket;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.GenericFutureListener;

import java.util.Date;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

public class Client {

    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        ChannelFuture connect = new Bootstrap()
                .group(eventExecutors)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) {
                        ch.pipeline()
                                .addLast(new StringEncoder())
                                .addLast(new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        System.out.println("我是客户端，我接收到服务器的消息了：" + msg);
                                    }
                                });

                    }
                })
                .connect("127.0.0.1", 8080);

        connect.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                new Thread(() -> {
                    Scanner scanner = new Scanner(System.in);
                    while (true){
                        String s = scanner.nextLine();
                        if("q".equals(s)){
                            channelFuture.channel().close();
                            break;
                        }
                        else{
                            // 建立好之后 发消息
                            channelFuture.channel().writeAndFlush(s);
                        }
                    }
                }).start();
            }
        });

        // 配置关闭事件
        ChannelFuture channelFuture = connect.channel().closeFuture();
        channelFuture.addListener((ChannelFutureListener) channelFuture1 -> {
            eventExecutors.shutdownGracefully();
        });
    }

}
